package com.hy.study.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;
import java.util.concurrent.Executors;

/**
 * 全局异常处理器
 *
 * @author huyong
 * @date 2024 年 01 月 05 日 17:22: 40
 */
@Slf4j
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    /**
     * 处理  400 Bad Request 异常
     *
     * @param e
     *
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HttpMessageNotReadableException.class, MissingServletRequestParameterException.class, BindException.class})
    public Result handlerHttpMessageNotReadableException(Exception e) {
        log.error("error  Bad Request:{}", e.getMessage());
        return new Result(StatusCode.BAD_REQUEST, "参数解析失败");

    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("error  Method Not Allowed: " + e.getMessage(), e);
        return new Result(StatusCode.METHOD_NOT_ALLOWED, "不支持当前请求方法");
    }

    /**
     * 自定义异常在此捕获
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Throwable.class)
    public Result handleException(Throwable e) {
        log.error("------err------Service Run Exception: " + e.getMessage(), e);
        if (e instanceof BSException) {
            return new Result(((BSException) e).getCode(), ((BSException) e).getMsg());
        }
        return new Result(StatusCode.SYSTEM_ERR, "服务器运行异常");
    }
}
